<template>
  <div>
    <el-table
      border
      stripe
      ref="studentTable"
      :data="propsTableData"
      style="width: 100%"
      highlight-current-row
    >
      <el-table-column
        v-for="(item, index) in tableField"
        :key="index"
        :label="item.label"
        align="center"
        :width="item.width"
      >
        <template #default="scope">
          <div v-if="item.type == 'upload' && scope.row.showFormDom">
            <el-upload
              ref="uploadRef"
              :show-file-list="false"
              :file-list="fileList[scope.$index]"
              :before-upload="beforeAvatarUpload"
              :on-remove="
                (res, file) => {
                  return handleRemoveImg(res, file)
                }
              "
              class="upload-demo"
              :on-success="handleAvatarSuccess"
              :action="uploadUrl"
              :limit="5"
            >
              <el-button
                class="el-icon-picture"
                size="small"
                plain
                type="primary"
                @click="upload(scope.$index)"
                >上传文件</el-button
              >
            </el-upload>
            <p class="link-div" v-show="scope.row.fileNameNum > 0">
              <span style="float: left">
                {{ propsTableData[scope.$index].fileNameNum }}个附件</span
              >
              <span
                v-show="tableFlag == 'add'"
                style="float: left"
                @click="clearFile(scope.$index)"
                ><el-icon><CircleClose /></el-icon
              ></span>
            </p>
          </div>
          <div
            class="link-div"
            v-else-if="item.type == 'upload' && !scope.row.showFormDom"
            @click="handleLink(scope.$index)"
          >
            <span style="float: left">
              {{ propsTableData[scope.$index].fileNameNum }}个附件</span
            >
          </div>
          <el-link
            v-else-if="item.type == 'documentName'"
            :href="propsTableData[scope.$index].filePath"
            target="_blank"
            class="color:#409eff"
            >{{ propsTableData[scope.$index].fileName }}</el-link
          >
          <!-- <el-link
            v-else-if="item.type == 'upload' && !scope.row.showFormDom"
            :href="propsTableData[scope.$index].filePath"
            target="_blank"
            >{{ propsTableData[scope.$index].fileName }}</el-link
          > -->

          <!-- 时间选择器 -->
          <el-date-picker
            v-else-if="item.type == 'date' && scope.row.showFormDom"
            style="width: 100%"
            class="item item-value"
            v-model="propsTableData[scope.$index][item.value]"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="选择日期"
            @change="changeDateTime"
          />

          <!-- 序号 -->
          <div v-else-if="item.value == 'index'">
            {{ scope.$index + 1 }}
          </div>
          <!-- 合同期限 -->
          <!-- <div v-else-if="item.value == 'contractType' && !scope.row.showFormDom">
            {{
              contractObj.find( item => item.id == propsTableData[scope.$index].contractType)?contractObj.find( item => item.id == propsTableData[scope.$index].contractType).name:''
            }}
          </div> -->

          <!-- 附件性质 -->
          <div v-else-if="item.value == 'documentNature'">
            {{
              documentNatureList.find(
                item => item.id == propsTableData[scope.$index].documentNature
              ).name
            }}
          </div>
          <!-- 输入框 -->

          <el-input
            v-else-if="item.type == 'input' && scope.row.showFormDom"
            v-model="propsTableData[scope.$index][item.value]"
            :placeholder="item.label"
          />

          <div v-else-if="item.type != 'upload' && !scope.row.showFormDom">
            {{ propsTableData[scope.$index][item.value] }}
          </div>

          <el-select
            v-else-if="item.value == 'contractType' && scope.row.showFormDom"
            v-model="propsTableData[scope.$index][item.value]"
            :placeholder="item.label"
            @change="changeSelect(scope.$index, item.value)"
          >
            <el-option
              v-for="(item, index) in contractObj"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="160px">
        <template #default="scope">
          <el-button
            link
            size="small"
            type="primary"
            icon="CircleCheck"
            @click="handleSave(scope.$index)"
            v-if="scope.row.showFormDom && tableName !== '附件资料'"
            >保存</el-button
          >
          <el-button
            v-else-if="tableFlag != 'add' && tableName != '附件资料'"
            link
            size="small"
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.$index)"
            >修改</el-button
          >
          <el-button
            link
            size="small"
            type="primary"
            icon="Delete"
            @click="handleRemove(scope.$index)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-button
      v-if="tableName != '附件资料'"
      style="width: 100%"
      class="el-icon-circle-plus-outline"
      @click="handleAdd()"
    >
      添加
    </el-button>
  </div>
</template>

<script setup name="Mytable">
import { computed, getCurrentInstance, reactive, toRefs } from 'vue'
import useUserStore from '../../../store/modules/user'
import { uploadAvatar } from '../../../api/system/user'
import { formatDate } from '@/utils'
const { proxy } = getCurrentInstance()

const data = reactive({
  uploadUrl: import.meta.env.VITE_APP_BASE_API + '/file/upload', // 上传的图片服务器地址
  curRow: -1,
  tableFlag: null,
  contractObj: [],
  fileList: [],
  propsTableData: [],
  fileNumber: 0,
  threeYear: null,
  indexNum: null,
  fileNumberName: '',
  //文档性质
  documentNatureList: [
    {
      id: 'tb_employee_study',
      name: '学习经历'
    },
    {
      id: 'tb_employee_contract',
      name: '合同信息'
    },
    {
      id: 'tb_employee_certificate',
      name: '取得证书'
    },
    {
      id: 'tb_employee_work',
      name: '工作经历'
    }
  ]
})
const {
  uploadUrl,
  curRow,
  fileList,
  propsTableData,
  fileNumber,
  threeYear,
  indexNum,
  fileNumberName,
  documentNatureList,
  tableFlag,
  contractObj
} = toRefs(data)
const props = defineProps({
  tableFlag: {
    type: String
  },
  tableField: {
    type: Array
  },
  tableData: {
    type: Array
  },
  tableName: {
    type: String
  },
  contractObj: {
    type: Array
  }
})

watch(
  () => props.tableData,
  (newVal, oldValue) => {
    propsTableData.value = newVal
    console.info('newVal', newVal)
    console.info('oldValue', oldValue)
    console.info('propsTableData.value', propsTableData.value)
  },
  {
    deep: true
  }
)
watch(
  () => props.tableFlag,
  val => {
    tableFlag.value = val
    console.info('tableFlag', tableFlag.value)
  },
  {
    deep: true
  }
)
watch(
  () => props.contractObj,
  val => {
    contractObj.value = val
    console.info('contractObj', contractObj.value)
  },
  {
    deep: true
  }
)
// const propsTableData = computed(() => {
//   return props.tableData
// })

const emit = defineEmits([
  'handleSave',
  'handleAdd',
  'handleRemove',
  'handleDel',
  'handleLink'
])
//初始化
async function init() {
  console.log('tableFlag', props.tableFlag)
}
init()
//合同期限
function changeSelect(index, item) {
  console.log('item', propsTableData.value[index].contractType)
  indexNum.value = index
  if (propsTableData.value[index].contractType == '1') {
    propsTableData.value[index].startDate = ''
    propsTableData.value[index].endDate = ''
  }
}
//起始日期
function changeDateTime(date) {
  if (
    indexNum.value != null &&
    propsTableData.value[indexNum.value].contractType == '1'
  ) {
    let nowDate = date ? date.split('-') : ''
    const year = Number(nowDate[0]) + 3
    let month = Number(nowDate[1])
    let day = Number(nowDate[2]) - 1
    month = month < 10 ? '0' + month : month
    day = day < 10 ? '0' + day : day
    threeYear.value = `${year}-${month}-${day}`
    propsTableData.value[indexNum.value].endDate = threeYear.value
  }
}

//跳转
function handleLink(index) {
  const activeName = '8'
  emit(
    'handleLink',
    propsTableData.value[index].employeeId,
    propsTableData.value[index].id,
    props.tableName,
    index,
    activeName
  )
}

// 保存
function handleSave(index) {
  console.log('保存', index)
  console.log(propsTableData.value[index])
  emit('handleSave', propsTableData.value[index], props.tableName, index)
}

// 修改
function handleUpdate(index) {
  propsTableData.value[index].contractType = contractObj.value.find(
    item => item.label == propsTableData.value[index].contractType
  )
    ? contractObj.value.find(
        item => item.label == propsTableData.value[index].contractType
      ).value
    : ''
  console.log('propsTableData====2222', propsTableData.value[index])
  propsTableData.value[index].showFormDom = true
  if (propsTableData.value[index].fileName) {
    fileList.value[index] = [
      {
        name: propsTableData.value[index].fileName,
        url: propsTableData.value[index].filePath
      }
    ]
  }
  console.log('修改====', fileList.value[index])
}

// 上传之前
function beforeAvatarUpload(file) {
  console.log('上传之前', file.name)
  //   propsTableData.value[curRow.value].fileName = file.name
}

// 删除图片
function handleRemoveImg(file, fileList) {
  console.log('删除图片')
  console.log(file, fileList)
  fileList.value = []
}

// 上传成功
function handleAvatarSuccess(res) {
  console.log('上传成功===', fileList.value, propsTableData.value[curRow.value])
  if (fileList.value.length > 0) {
    propsTableData.value[curRow.value].filePath =
      fileList.value[curRow.value][0].url
    propsTableData.value[curRow.value].fileName =
      fileList.value[curRow.value][0].name
  }

  if (res.code == 200) {
    if (propsTableData.value[curRow.value].fileName) {
      propsTableData.value[curRow.value].filePath =
        propsTableData.value[curRow.value].filePath + ',' + res.data.url
      propsTableData.value[curRow.value].fileName =
        propsTableData.value[curRow.value].fileName +
        ',' +
        res.data.origFileName
    } else {
      propsTableData.value[curRow.value].filePath = res.data.url
      propsTableData.value[curRow.value].fileName = res.data.origFileName
    }

    propsTableData.value[curRow.value].fileNameNum =
      propsTableData.value[curRow.value].fileName.split(',').length
  } else {
    console.log(propsTableData.value)
    propsTableData.value[curRow.value].fileName = ''
    propsTableData.value[curRow.value].filePath = ''
    proxy.$modal.msgError(res.msg)
  }
}
// 上传证书
function upload(index) {
  curRow.value = index
}
//清除文件
function clearFile(index) {
  //   proxy.$refs.uploadRef.clearFiles()
  fileList.value[index] = []
  propsTableData.value[index].fileName = ''
  propsTableData.value[index].filePath = ''
  propsTableData.value[index].fileNameNum = 0
  fileNumber.value = 0
  console.log(
    '清除===',
    index,
    fileList.value,
    propsTableData.value[index].fileName
  )
}
// 上传图片
function uploadImg() {
  proxy.$refs.cropper.getCropBlob(data => {
    let formData = new FormData()
    formData.append('avatarfile', data)
    uploadAvatar(formData).then(response => {
      open.value = false
      let img = import.meta.env.VITE_APP_BASE_API + response.imgUrl
      // store.commit('SET_AVATAR', this.options.img);
      useUserStore().uploadAvatar(img)
      proxy.$modal.msgSuccess('修改成功')
      // visible = false
    })
  })
}

// 添加
function handleAdd() {
  emit('handleAdd')
}

// 删除
function handleRemove(index) {
  proxy
    .$confirm('确认删除选中记录吗？', '提示', {
      type: 'warning'
    })
    .then(() => {
      if (propsTableData.value[index].id) {
        emit('handleRemove', propsTableData.value[index].id, props.tableName)
      } else {
        emit('handleDel', props.tableName)
        console.info('props.tableName', props.tableName)
        propsTableData.value.splice(index, 1)
        proxy.$modal.msgSuccess({
          message: '删除成功',
          type: 'success'
        })
      }
    })
}
// export default {
//   name: '',
//   props: {
//     tableField: {
//       type: Array
//     },
//     tableData: {
//       type: Array
//     },
//     tableName: {
//       type: String
//     },
//   },
//   data() {
//     return {
//
//     }
//   },
//   methods:
//   {
//
//
//
//   }
// }
</script>

<style style scoped lang="scss">
::v-deep .el-table .el-table__header-wrapper th {
  background-color: #f5f7fa !important;
  color: #000018 !important;
}

::v-deep .el-table--border th,
::v-deep .el-table--border td {
  border-right: 1px solid #eee;
}
::v-deep .el-link {
  color: #409eff;
}
.link-div {
  cursor: pointer;
  color: #409eff;
  display: inline-block;
}
</style>
